using System.Data.SqlClient;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate.ByteCode.Castle;
using NHibernate.Cfg;
using Environment = NHibernate.Cfg.Environment;

namespace Web.Extensions
{
	public class SqlServerDatabaseConfiguration : DatabaseConfigurationBase
	{
		public SqlServerDatabaseConfiguration()
		{
			//Server = @"(local)\SQLEXPRESS";
			//Database = "volunteers";

			
		}

		public override void CreateNew()
		{
			const string script =
				@"IF exists(SELECT * FROM sysdatabases WHERE [Name] = '{0}')
					DROP DATABASE {0}
				CREATE DATABASE {0}";

			var connStrBuilder = new SqlConnectionStringBuilder { DataSource = Server, InitialCatalog = "master" };
			if (Username == null && Password == null)
				connStrBuilder.IntegratedSecurity = true;
			else
			{
				connStrBuilder.UserID = Username;
				connStrBuilder.Password = Password;
			}

			using (var conn = new SqlConnection(connStrBuilder.ToString()))
			{
				conn.Open();
				using (var cmd = conn.CreateCommand())
				{
					cmd.CommandText = string.Format(script, Database);
					cmd.ExecuteNonQuery();
				}
			}
		}

		protected override Configuration BuildConfiguration()
		{
			return Fluently
				.Configure()
				.Database(MsSqlConfiguration
							.MsSql2008
							.ConnectionString(c =>
							{
								c.Server(Server).Database(Database);

								if (Username == null && Password == null)
									c.TrustedConnection();
								else
									c.Username(Username).Password(Password);
							}
							)
				//.ShowSql()
				)
				.Mappings(m => m.FluentMappings.AddFromAssemblyOf<IDatabaseConfiguration>())
				.BuildConfiguration()
				.SetProperty(Environment.ProxyFactoryFactoryClass, typeof(ProxyFactoryFactory).AssemblyQualifiedName)
				.SetProperty(Environment.CurrentSessionContextClass, "thread_static");
			//.SetProperty(Environment.TransactionStrategy, typeof(AdoNetTransactionFactory).FullName);
		}

		public string Password { get; set; }

		public string Username { get; set; }

		public string Database { get; set; }

		public string Server { get; set; }
	}
}